/**
 * 供应商档案 - 主界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.Supplier.MainForm", {
  extend: "PSI.AFX.Form.MainForm",

  config: {
    pAddCategory: null,
    pEditCategory: null,
    pDeleteCategory: null,
    pAddSupplier: null,
    pEditSupplier: null,
    pDeleteSupplier: null
  },

  /**
   * @override
   */
  initComponent() {
    const me = this;

    PCL.apply(me, {
      items: [{
        tbar: me.getToolbarCmp(),
        id: me.buildId(me, "panelQueryCmp"),
        region: "north",
        height: 95,
        border: 0,
        collapsible: true,
        collapseMode: "mini",
        header: false,
        layout: {
          type: "table",
          columns: 6
        },
        bodyCls: "PSI-Query-Panel",
        items: me.getQueryCmp()
      }, {
        region: "center",
        layout: "border",
        border: 0,
        ...PSI.Const.BODY_PADDING,
        items: [{
          region: "center",
          xtype: "panel",
          layout: "border",
          border: 0,
          items: [{
            region: "center",
            layout: "fit",
            border: 0,
            items: [me.getMainGrid()]
          }, {
            region: "south",
            height: 200,
            layout: "border",
            split: true,
            collapsible: true,
            border: 0,
            id: "panelGoodsRange",
            header: {
              height: 30,
              title: me.formatGridHeaderTitle("关联商品")
            },
            bodyStyle: "border-width:0px",
            items: [{
              region: "center",
              layout: "fit",
              border: 0,
              items: [me.getGRCategoryGrid()]
            }, {
              region: "east",
              width: "50%",
              layout: "fit",
              split: true,
              border: 0,
              items: [me.getGRGoodsGrid()]
            }]
          }]
        }, {
          id: "panelCategory",
          xtype: "panel",
          region: "west",
          layout: "fit",
          width: 370,
          split: true,
          collapsible: true,
          header: false,
          border: 0,
          items: [me.getCategoryGrid()]
        }]
      }]
    });

    me.callParent(arguments);

    me._dfSupplierInfo = PCL.getCmp(me.buildId(me, "dfSupplierInfo"));

    me.editQueryCode = PCL.getCmp(me.buildId(me, "editQueryCode"));
    me.editQueryName = PCL.getCmp(me.buildId(me, "editQueryName"));
    me.editQueryAddress = PCL.getCmp(me.buildId(me, "editQueryAddress"));
    me.editQueryContact = PCL.getCmp(me.buildId(me, "editQueryContact"));
    me.editQueryMobile = PCL.getCmp(me.buildId(me, "editQueryMobile"));
    me.editQueryTel = PCL.getCmp(me.buildId(me, "editQueryTel"));
    me.editQueryQQ = PCL.getCmp(me.buildId(me, "editQueryQQ"));
    me.editQueryRecordStatus = PCL.getCmp(me.buildId(me, "editQueryRecordStatus"));

    // AFX
    me.__editorList = [
      me.editQueryCode, me.editQueryName, me.editQueryAddress,
      me.editQueryContact, me.editQueryMobile, me.editQueryTel,
      me.editQueryQQ, me.editQueryRecordStatus
    ];

    me._keyMapMain = PCL.create("PCL.util.KeyMap", PCL.getBody(), [{
      key: "N",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        // 判断权限
        if (me.getPAddSupplier() != "1") {
          return;
        }

        me._onAddSupplier.apply(me, []);
      },
      scope: me
    }, {
      key: "Q",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }
        PCL.getCmp(me.buildId(me, "editQueryCode"))?.focus();
      },
      scope: me
    }, {
      key: "H",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        const panel = PCL.getCmp(me.buildId(me, "panelQueryCmp"));
        if (panel.getCollapsed()) {
          panel.expand();
        } else {
          panel.collapse();
        };
      },
      scope: me
    },
    ]);


    me.freshCategoryGrid();
  },

  /**
   * @private
   */
  getToolbarCmp() {
    const me = this;

    const result = [];
    const list = [];
    if (me.getPAddCategory() == "1") {
      list.push({
        text: "新建供应商分类",
        ...PSI.Const.BTN_STYLE,
        handler: me._onAddCategory,
        scope: me
      });
    }
    if (me.getPEditCategory() == "1") {
      list.push({
        text: "编辑供应商分类",
        ...PSI.Const.BTN_STYLE,
        handler: me._onEditCategory,
        scope: me
      });
    }
    if (me.getPDeleteCategory() == "1") {
      list.push({
        text: "删除供应商分类",
        ...PSI.Const.BTN_STYLE,
        handler: me._onDeleteCategory,
        scope: me
      });
    }
    if (list.length > 0) {
      result.push({
        text: "供应商分类",
        iconCls: "PSI-tb-new",
        ...PSI.Const.BTN_STYLE,
        menu: list
      });
    }

    let sep = list.length > 0;

    if (me.getPAddSupplier() == "1") {
      if (sep) {
        result.push("-");
        sep = false;
      }

      result.push({
        iconCls: "PSI-tb-new-entity",
        text: "新建供应商 <span class='PSI-shortcut-DS'>Alt + N</span>",
        tooltip: "快捷键：Alt + N",
        ...PSI.Const.BTN_STYLE,
        handler: me._onAddSupplier,
        scope: me
      });
    }
    if (me.getPEditSupplier() == "1") {
      if (sep) {
        result.push("-");
        sep = false;
      }

      result.push({
        text: "编辑供应商",
        ...PSI.Const.BTN_STYLE,
        handler: me._onEditSupplier,
        scope: me
      });
    }
    if (me.getPDeleteSupplier() == "1") {
      if (sep) {
        result.push("-");
        sep = false;
      }
      result.push({
        text: "删除供应商",
        ...PSI.Const.BTN_STYLE,
        handler: me._onDeleteSupplier,
        scope: me
      });
    }

    sep = result.length > 0;
    if (sep) {
      result.push("-");
      sep = false;
    }
    result.push({
      iconCls: "PSI-tb-help",
      text: "指南",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        window.open(me.URL("Home/Help/index?t=supplier"));
      }
    }, "-", {
      iconCls: "PSI-tb-close",
      text: "关闭",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        me.closeWindow();
      }
    }, {
      // 空容器，只是为了撑高工具栏
      xtype: "container", height: 28,
      items: []
    });

    return result.concat(me.getShortcutCmp());
  },

  /**
   * 快捷访问
   * 
   * @private
   */
  getShortcutCmp() {
    return ["->",
      {
        cls: "PSI-Shortcut-Cmp",
        labelWidth: 0,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield",
        width: 90
      }
    ];
  },

  /**
   * @private
   */
  getQueryCmp() {
    const me = this;

    return [{
      xtype: "container",
      height: 26,
      html: `<h2 style='margin-left:20px;margin-top:18px;color:#595959;display:inline-block'>供应商档案</h2>
              &nbsp;&nbsp;<span style='color:#8c8c8c'>主数据</span>
              <div style='float:right;display:inline-block;margin:10px 0px 0px 20px;border-left:1px solid #e5e6e8;height:40px'>&nbsp;</div>
              `
    }, {
      id: me.buildId(me, "editQueryCode"),
      labelWidth: 115,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "供应商编码 <span class='PSI-shortcut-DS'>Alt + Q</span>",
      width: 235,
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryName"),
      labelWidth: 70,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "供应商名称",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryAddress"),
      labelWidth: 60,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "地址",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryContact"),
      labelWidth: 70,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "联系人",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      },
      width: 240
    }, {
      id: me.buildId(me, "editQueryMobile"),
      labelWidth: 70,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "手机",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, { xtype: "container" }, {
      id: me.buildId(me, "editQueryTel"),
      labelWidth: 80,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "固话",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryQQ"),
      labelWidth: 70,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "QQ",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryRecordStatus"),
      xtype: "combo",
      queryMode: "local",
      editable: false,
      valueField: "id",
      labelWidth: 60,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "状态",
      margin: "5, 0, 0, 0",
      store: PCL.create("PCL.data.ArrayStore", {
        fields: ["id", "text"],
        data: [[-1, "全部"], [1000, "启用"], [0, "停用"]]
      }),
      value: -1,
      listeners: {
        specialkey: {
          fn: me.__onLastEditSpecialKey,
          scope: me
        }
      }
    }, {
      xtype: "container",
      items: [{
        xtype: "button",
        text: "查询",
        cls: "PSI-Query-btn1",
        width: 100,
        height: 26,
        margin: "5, 0, 0, 20",
        handler: me._onQuery,
        scope: me
      }, {
        xtype: "button",
        text: "清空查询条件",
        cls: "PSI-Query-btn2",
        width: 100,
        height: 26,
        margin: "5, 0, 0, 15",
        handler: me._onClearQuery,
        scope: me
      }]
    }, {
      xtype: "container",
      items: [{
        xtype: "button",
        text: "隐藏工具栏 <span class='PSI-shortcut-DS'>Alt + H</span>",
        cls: "PSI-Query-btn3",
        width: 140,
        height: 26,
        iconCls: "PSI-button-hide",
        margin: "5 0 0 20",
        handler() {
          PCL.getCmp(me.buildId(me, "panelQueryCmp")).collapse();
        },
        scope: me
      }]
    }];
  },

  /**
   * @private
   */
  getCategoryGrid() {
    const me = this;
    if (me._categoryGrid) {
      return me._categoryGrid;
    }

    const modelName = me.buildModelName(me, "SupplierCategory");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "code", "name", {
        name: "cnt",
        type: "int"
      }]
    });

    me._categoryGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-FC",
      viewConfig: {
        enableTextSelection: true
      },
      header: {
        height: 30,
        title: me.formatGridHeaderTitle("供应商分类")
      },
      tools: [{
        type: "close",
        handler() {
          PCL.getCmp("panelCategory").collapse();
        }
      }],
      features: [{
        ftype: "summary"
      }],
      columnLines: true,
      columns: [{
        header: "分类编码",
        dataIndex: "code",
        width: 80,
        menuDisabled: true,
        sortable: false
      }, {
        header: "供应商分类",
        dataIndex: "name",
        width: 160,
        menuDisabled: true,
        sortable: false,
        summaryRenderer() {
          return "供应商个数合计";
        }
      }, {
        header: "供应商个数",
        dataIndex: "cnt",
        width: 100,
        menuDisabled: true,
        sortable: false,
        summaryType: "sum",
        align: "right"
      }],
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {
        select: {
          fn: me._onCategoryGridSelect,
          scope: me
        },
        itemdblclick: {
          fn: me._onEditCategory,
          scope: me
        }
      }
    });

    return me._categoryGrid;
  },

  /**
   * @private
   */
  getMainGrid() {
    const me = this;
    if (me._mainGrid) {
      return me._mainGrid;
    }

    const modelName = me.buildModelName(me, "Supplier");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "code", "name", "contact01", "tel01",
        "mobile01", "qq01", "contact02", "tel02",
        "mobile02", "qq02", "categoryId", "initPayables",
        "initPayablesDT", "address", "addressShipping",
        "bankName", "bankAccount", "tax", "fax", "note",
        "dataOrg", "taxRate", "recordStatus", "goodsRange"]
    });

    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: [],
      pageSize: 20,
      proxy: {
        type: "ajax",
        actionMethods: {
          read: "POST"
        },
        url: me.URL("SLN0001/Supplier/supplierList"),
        reader: {
          root: 'supplierList',
          totalProperty: 'totalCount'
        }
      },
      listeners: {
        beforeload: {
          fn() {
            store.proxy.extraParams = me.getQueryParam();
          },
          scope: me
        },
        load: {
          fn(e, records, successful) {
            if (successful) {
              me.refreshCategoryCount();
              me.gotoSupplierGridRecord(me._lastId);
            }
          },
          scope: me
        }
      }
    });

    me._mainGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-LC",
      viewConfig: {
        enableTextSelection: true
      },
      columnLines: true,
      columns: {
        defaults: {
          menuDisabled: true,
          sortable: false
        },
        items: [PCL.create("PCL.grid.RowNumberer", {
          text: "#",
          width: 40
        }), {
          header: "供应商编码",
          locked: true,
          dataIndex: "code",
          renderer(value, metaData, record) {
            if (parseInt(record.get("recordStatus")) == 1000) {
              return value;
            } else {
              return `<span class="PSI-record-disabled">${value}</span>`;
            }
          }
        }, {
          header: "供应商名称",
          locked: true,
          dataIndex: "name",
          width: 300,
          renderer(value, metaData, record) {
            if (parseInt(record.get("recordStatus")) == 1000) {
              return value;
            } else {
              return `<span class="PSI-record-disabled">${value}</span>`;
            }
          }
        }, {
          header: "地址",
          dataIndex: "address",
          width: 300
        }, {
          header: "联系人",
          dataIndex: "contact01"
        }, {
          header: "手机",
          dataIndex: "mobile01"
        }, {
          header: "固话",
          dataIndex: "tel01"
        }, {
          header: "QQ",
          dataIndex: "qq01"
        }, {
          header: "备用联系人",
          dataIndex: "contact02"
        }, {
          header: "备用联系人手机",
          dataIndex: "mobile02",
          width: 150
        }, {
          header: "备用联系人固话",
          dataIndex: "tel02",
          width: 150
        }, {
          header: "备用联系人QQ",
          dataIndex: "qq02",
          width: 150
        }, {
          header: "发货地址",
          dataIndex: "addressShipping",
          width: 300
        }, {
          header: "开户行",
          dataIndex: "bankName"
        }, {
          header: "开户行账号",
          dataIndex: "bankAccount"
        }, {
          header: "社会统一信用代码",
          dataIndex: "tax",
          width: 150,
        }, {
          header: "传真",
          dataIndex: "fax"
        }, {
          header: "税率(%)",
          align: "right",
          dataIndex: "taxRate"
        }, {
          header: "应付期初余额",
          dataIndex: "initPayables",
          align: "right",
          xtype: "numbercolumn"
        }, {
          header: "应付期初余额日期",
          dataIndex: "initPayablesDT",
          width: 150
        }, {
          header: "关联物料的范围",
          dataIndex: "goodsRange",
          width: 120,
          renderer(value) {
            return value == 1
              ? "全部物料"
              : "<span style='color:red'>部分设置的物料</span>";
          }
        }, {
          header: "备注",
          dataIndex: "note",
          width: 400
        }, {
          header: "数据域",
          dataIndex: "dataOrg"
        }, {
          header: "状态",
          dataIndex: "recordStatus",
          renderer(value) {
            if (parseInt(value) == 1000) {
              return "启用";
            } else {
              return "<span style='color:red'>停用</span>";
            }
          }
        }]
      },
      store: store,
      tbar: ["", {
        xtype: "displayfield",
        id: me.buildId(me, "dfSupplierInfo"),
        value: "供应商列表",
      }, "->", {
          id: "pagingToolbar",
          border: 0,
          xtype: "pagingtoolbar",
          store: store
        }, "-", {
          xtype: "displayfield",
          value: "每页显示"
        }, {
          id: "comboCountPerPage",
          xtype: "combobox",
          editable: false,
          width: 60,
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["text"],
            data: [["20"], ["50"], ["100"], ["300"],
            ["1000"]]
          }),
          value: 20,
          listeners: {
            change: {
              fn() {
                store.pageSize = PCL.getCmp("comboCountPerPage").getValue();
                store.currentPage = 1;
                PCL.getCmp("pagingToolbar").doRefresh();
              },
              scope: me
            }
          }
        }, {
          xtype: "displayfield",
          value: "条记录"
        }],
      listeners: {
        itemdblclick: {
          fn: me._onEditSupplier,
          scope: me
        },
        select: {
          fn: me._onSupplierSelect,
          scope: me
        }
      }
    });

    return me._mainGrid;
  },

  /**
   * 新建供应商分类
   * 
   * @private
   */
  _onAddCategory() {
    const me = this;

    const form = PCL.create("PSI.SLN0001.Supplier.CategoryEditForm", {
      parentForm: me,
      renderTo: PSI.Const.RENDER_TO(),
    });

    form.show();
  },

  /**
   * 编辑供应商分类
   * 
   * @private
   */
  _onEditCategory() {
    const me = this;
    if (me.getPEditCategory() == "0") {
      return;
    }

    const item = me.getCategoryGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要编辑的供应商分类");
      return;
    }

    const category = item[0];

    const form = PCL.create("PSI.SLN0001.Supplier.CategoryEditForm", {
      parentForm: me,
      entity: category,
      renderTo: PSI.Const.RENDER_TO(),
    });

    form.show();
  },

  /**
   * 删除供应商分类
   * 
   * @private
   */
  _onDeleteCategory() {
    const me = this;

    const item = me.getCategoryGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      PSI.MsgBox.showInfo("请选择要删除的供应商分类");
      return;
    }

    const category = item[0];
    const info = "请确认是否删除供应商分类: <span style='color:red'>"
      + category.get("name") + "</span>";

    const store = me.getCategoryGrid().getStore();
    let index = store.findExact("id", category.get("id"));
    index--;
    let preIndex = null;
    const preItem = store.getAt(index);
    if (preItem) {
      preIndex = preItem.get("id");
    }

    me.confirm(info, () => {
      const el = PCL.getBody();
      el?.mask("正在删除中...");
      me.ajax({
        url: me.URL("SLN0001/Supplier/deleteCategory"),
        params: {
          id: category.get("id")
        },
        callback(options, success, response) {
          el?.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.tip("成功完成删除操作", true);
              me.freshCategoryGrid(preIndex);
            } else {
              me.showInfo(data.msg);
            }
          }
        }
      });
    });
  },

  /**
   * @private
   */
  freshCategoryGrid(id) {
    const me = this;
    const grid = me.getCategoryGrid();
    const el = grid.getEl() || PCL.getBody();
    el.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/Supplier/categoryList"),
      params: me.getQueryParam(),
      callback(options, success, response) {
        const store = grid.getStore();

        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);

          if (id) {
            const r = store.findExact("id", id);
            if (r != -1) {
              grid.getSelectionModel().select(r);
            }
          } else {
            grid.getSelectionModel().select(0);
          }
        }

        el.unmask();
      }
    });
  },

  /**
   * @private
   */
  freshSupplierGrid(id) {
    const me = this;

    const item = me.getCategoryGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me._dfSupplierInfo.setValue("供应商列表");
      return;
    }

    const category = item[0];

    const info = `<span class='PSI-title-keyword'>${category.get("name")}</span> - 供应商列表`;
    me._dfSupplierInfo.setValue(info);

    me._lastId = id;
    PCL.getCmp("pagingToolbar").doRefresh()
  },

  /**
   * @private
   */
  _onCategoryGridSelect() {
    const me = this;
    me.getMainGrid().getStore().currentPage = 1;
    me.freshSupplierGrid();
  },

  /**
   * @private
   */
  _onAddSupplier() {
    const me = this;

    if (me.getCategoryGrid().getStore().getCount() == 0) {
      me.showInfo("没有供应商分类，请先新建供应商分类");
      return;
    }

    const form = PCL.create("PSI.SLN0001.Supplier.SupplierEditForm", {
      parentForm: me,
      renderTo: PSI.Const.RENDER_TO(),
    });

    form.show();
  },

  /**
   * 编辑供应商档案
   * 
   * @private
   */
  _onEditSupplier() {
    const me = this;
    if (me.getPEditSupplier() == "0") {
      return;
    }

    let item = me.getCategoryGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择供应商分类");
      return;
    }
    const category = item[0];

    item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要编辑的供应商");
      return;
    }

    const supplier = item[0];
    supplier.set("categoryId", category.get("id"));
    const form = PCL.create("PSI.SLN0001.Supplier.SupplierEditForm", {
      parentForm: me,
      entity: supplier,
      renderTo: PSI.Const.RENDER_TO(),
    });

    form.show();
  },

  /**
   * @private
   */
  _onDeleteSupplier() {
    const me = this;
    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要删除的供应商");
      return;
    }

    const supplier = item[0];

    const store = me.getMainGrid().getStore();
    let index = store.findExact("id", supplier.get("id"));
    index--;
    let preIndex = null;
    const preItem = store.getAt(index);
    if (preItem) {
      preIndex = preItem.get("id");
    }

    const info = `请确认是否删除供应商: <span style='color:red'>${supplier.get("name")}</span>`;
    me.confirm(info, () => {
      const el = PCL.getBody();
      el.mask("正在删除中...");
      me.ajax({
        url: me.URL("SLN0001/Supplier/deleteSupplier"),
        params: {
          id: supplier.get("id")
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.tip("成功完成删除操作", true);
              me.freshSupplierGrid(preIndex);
            } else {
              me.showInfo(data.msg);
            }
          }
        }
      });
    });
  },

  /**
   * @private
   */
  gotoCategoryGridRecord(id) {
    const me = this;
    const grid = me.getCategoryGrid();
    const store = grid.getStore();
    if (id) {
      const r = store.findExact("id", id);
      if (r != -1) {
        grid.getSelectionModel().select(r);
      } else {
        grid.getSelectionModel().select(0);
      }
    }
  },

  /**
   * @private
   */
  gotoSupplierGridRecord(id) {
    const me = this;
    const grid = me.getMainGrid();
    const store = grid.getStore();
    if (id) {
      const r = store.findExact("id", id);
      if (r != -1) {
        grid.getSelectionModel().select(r);
        grid.getSelectionModel().setLastFocused(store.getAt(r));
      } else {
        grid.getSelectionModel().select(0);
      }
    } else {
      grid.getSelectionModel().select(0);
    }
  },

  /**
   * @private
   */
  refreshCategoryCount() {
    const me = this;
    const item = me.getCategoryGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const category = item[0];
    category.set("cnt", me.getMainGrid().getStore().getTotalCount());
    me.getCategoryGrid().getStore().commitChanges();
  },

  /**
   * @private
   */
  getQueryParam() {
    const me = this;
    const item = me.getCategoryGrid().getSelectionModel().getSelection();
    let categoryId;
    if (item == null || item.length != 1) {
      categoryId = null;
    } else {
      categoryId = item[0].get("id");
    }

    const result = {
      categoryId: categoryId
    };

    const code = me.editQueryCode.getValue();
    if (code) {
      result.code = code;
    }

    const address = me.editQueryAddress.getValue();
    if (address) {
      result.address = address;
    }

    const name = me.editQueryName.getValue();
    if (name) {
      result.name = name;
    }

    const contact = me.editQueryContact.getValue();
    if (contact) {
      result.contact = contact;
    }

    const mobile = me.editQueryMobile.getValue();
    if (mobile) {
      result.mobile = mobile;
    }

    const tel = me.editQueryTel.getValue();
    if (tel) {
      result.tel = tel;
    }

    const qq = me.editQueryQQ.getValue();
    if (qq) {
      result.qq = qq;
    }

    result.recordStatus = me.editQueryRecordStatus.getValue();

    return result;
  },

  /**
   * @private
   */
  _onQuery() {
    const me = this;

    me.getMainGrid().getStore().removeAll();
    me.freshCategoryGrid();
  },

  /**
   * @private
   */
  _onClearQuery() {
    const me = this;

    me.editQueryCode.setValue("");
    me.editQueryName.setValue("");
    me.editQueryAddress.setValue("");
    me.editQueryContact.setValue("");
    me.editQueryMobile.setValue("");
    me.editQueryTel.setValue("");
    me.editQueryQQ.setValue("");

    me.editQueryRecordStatus.setValue(-1);

    me._onQuery();
  },

  /**
   * 关联物料 - 按物料类别设置
   * 
   * @private
   */
  getGRCategoryGrid() {
    const me = this;
    if (me._grcategoryGrid) {
      return me._grcategoryGrid;
    }

    const modelName = me.buildModelName(me, "SupplierGRCategory");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "code", "name"]
    });

    me._grcategoryGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-HL",
      viewConfig: {
        enableTextSelection: true
      },
      header: {
        height: 30,
        title: me.formatGridHeaderTitle("按物料分类设置")
      },
      selModel: {
        mode: "MULTI"
      },
      selType: "checkboxmodel",
      tbar: [{
        iconCls: "PSI-tb-new-subentity",
        text: "添加物料分类",
        ...PSI.Const.BTN_STYLE,
        scope: me,
        handler: me._onAddGRCategory
      }, "-", {
        text: "移除物料分类",
        ...PSI.Const.BTN_STYLE,
        scope: me,
        handler: me._onDeleteGRCategory
      }],
      columnLines: true,
      columns: [{
        header: "物料分类编码",
        dataIndex: "code",
        width: 120,
        menuDisabled: true,
        sortable: false
      }, {
        header: "物料分类",
        dataIndex: "name",
        width: 160,
        menuDisabled: true,
        sortable: false
      }],
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {}
    });

    return me._grcategoryGrid;
  },

  /**
   * 关联物料 - 个别物料设置
   * 
   * @private
   */
  getGRGoodsGrid() {
    const me = this;
    if (me._grgoodsGrid) {
      return me._grgoodsGrid;
    }

    const modelName = me.buildModelName(me, "SupplierGRGoods");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "code", "name", "spec"]
    });

    me._grgoodsGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-HL",
      viewConfig: {
        enableTextSelection: true
      },
      header: {
        height: 30,
        title: me.formatGridHeaderTitle("按个别物料设置")
      },
      selModel: {
        mode: "MULTI"
      },
      selType: "checkboxmodel",
      tbar: [{
        iconCls: "PSI-tb-new-subentity",
        text: "添加物料",
        ...PSI.Const.BTN_STYLE,
        scope: me,
        handler: me._onAddGRGoods
      }, "-", {
        text: "移除物料",
        ...PSI.Const.BTN_STYLE,
        scope: me,
        handler: me._onDeleteGRGoods
      }],
      columnLines: true,
      columns: [{
        header: "物料编码",
        dataIndex: "code",
        width: 120,
        menuDisabled: true,
        sortable: false
      }, {
        header: "品名",
        dataIndex: "name",
        width: 160,
        menuDisabled: true,
        sortable: false
      }, {
        header: "规格型号",
        dataIndex: "spec",
        width: 160,
        menuDisabled: true,
        sortable: false
      }],
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {}
    });

    return me._grgoodsGrid;
  },

  /**
   * @private
   */
  _onAddGRCategory() {
    const me = this;

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要设置关联物料的供应商");
      return;
    }

    const supplier = item[0];

    const form = PCL.create("PSI.SLN0001.Supplier.GRCategoryEditForm", {
      entity: supplier,
      parentForm: me,
      renderTo: PSI.Const.RENDER_TO(),
    });
    form.show();
  },

  /**
   * @private
   */
  _onDeleteGRCategory() {
    const me = this;
    let item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择供应商");
      return;
    }

    const supplier = item[0];

    item = me.getGRCategoryGrid().getSelectionModel().getSelection();
    if (item == null || item.length == 0) {
      me.showInfo("没有选择要移除的物料分类");
      return;
    }

    const idArray = [];
    for (let i = 0; i < item.length; i++) {
      idArray.push(item[i].get("id"));
    }

    const info = "请确认是否要移除选中的物料分类?";
    const confirmFunc = () => {
      const el = PCL.getBody();
      el.mask("正在删除中...");
      const r = {
        url: me.URL("SLN0001/Supplier/deleteGRCategory"),
        params: {
          id: supplier.get("id"),
          idList: idArray.join(",")
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.tip("成功完成删除操作", true);
              me.refreshGRCategoryGrid();
            } else {
              me.showInfo(data.msg);
            }
          }
        }
      };
      me.ajax(r);
    };

    me.confirm(info, confirmFunc);
  },

  /**
   * @private
   */
  _onAddGRGoods() {
    const me = this;

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要设置关联物料的供应商");
      return;
    }

    const supplier = item[0];

    const form = PCL.create("PSI.SLN0001.Supplier.GRGoodsEditForm", {
      entity: supplier,
      parentForm: me,
      renderTo: PSI.Const.RENDER_TO(),
    });
    form.show();
  },

  /**
   * @private
   */
  _onDeleteGRGoods() {
    const me = this;
    let item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择供应商");
      return;
    }

    const supplier = item[0];

    item = me.getGRGoodsGrid().getSelectionModel().getSelection();
    if (item == null || item.length == 0) {
      me.showInfo("没有选择要移除的个别物料");
      return;
    }

    const idArray = [];
    for (let i = 0; i < item.length; i++) {
      idArray.push(item[i].get("id"));
    }

    const info = "请确认是否要移除选中的物料?";
    const confirmFunc = () => {
      const el = PCL.getBody();
      el.mask("正在删除中...");
      const r = {
        url: me.URL("SLN0001/Supplier/deleteGRGoods"),
        params: {
          id: supplier.get("id"),
          idList: idArray.join(",")
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.tip("成功完成删除操作", true);
              me.refreshGRGoodsGrid();
            } else {
              me.showInfo(data.msg);
            }
          }
        }
      };
      me.ajax(r);
    };

    me.confirm(info, confirmFunc);
  },

  /**
   * @private
   */
  _onSupplierSelect() {
    const me = this;
    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const supplier = item[0];
    const goodsRange = supplier.get("goodsRange");

    let info = "供应商[" + supplier.get("name") + "]";
    if (goodsRange == 1) {
      info += "能使用<strong>全部物料</strong>(<span class='PSI-field-note'>下表的设置不生效</span>)";
    } else {
      info += "只能使用如下设置中的<strong>关联物料</strong>";
    }
    info = "<span style='font-size:120%;'>" + info + "</span>";
    PCL.getCmp("panelGoodsRange").setTitle(info);

    me.refreshGRCategoryGrid();
    me.refreshGRGoodsGrid();
  },

  /**
   * @private
   */
  refreshGRCategoryGrid() {
    const me = this;
    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const supplier = item[0];

    const grid = me.getGRCategoryGrid();
    const el = grid.getEl() || PCL.getBody();
    el.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/Supplier/grCategoryList"),
      params: {
        id: supplier.get("id")
      },
      callback(options, success, response) {
        const store = grid.getStore();

        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
        }

        el.unmask();
      }
    });
  },

  /**
   * @private
   */
  refreshGRGoodsGrid() {
    const me = this;
    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const supplier = item[0];

    const grid = me.getGRGoodsGrid();
    const el = grid.getEl() || PCL.getBody();
    el.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/Supplier/grGoodsList"),
      params: {
        id: supplier.get("id")
      },
      callback(options, success, response) {
        const store = grid.getStore();

        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
        }

        el.unmask();
      }
    });
  }
});
